import { MciButton, MciDialog, MciSvgIcon } from '@/components/base';
import { ElPopover, ElUpload } from 'element-plus';
import FileSaver from 'file-saver';
import { getDecisionFlowGet } from '@/api/decision-engine';
import { decisionKey } from '../../types';

export const DesignMore = defineComponent({
  props: {
    flowId: {
      type: String,
      default: ''
    },
    decisionId: {
      type: String,
      default: ''
    },
    categoryId: {
      type: String,
      default: ''
    },
    flowName: {
      type: String,
      default: ''
    }
    // flowStatus: {
    //   type: Number,
    //   default: 0
    // },
    // permissionRoles: {
    //   type: Object,
    //   default: () => {}
    // }
  },
  // emits: ['refreshList'],
  setup(props) {
    // 导入决策
    const router = useRouter();
    const { setImportJSON } = inject(decisionKey);
    // 导出
    const visibleImport = ref(false);
    const fileList = ref([]);

    return () => (
      <>
        <div class="flex gap-12 ml-12">
          <ElPopover popperClass="popover-node-list" trigger="click">
            {{
              reference() {
                return (
                  <div onClick={(e) => e.stopPropagation()} class="cursor-pointer">
                    {/* <ElTooltip placement="bottom" content="更多">
                        <MciSvgIcon name="more" class="cursor-pointer" />
                      </ElTooltip> */}
                    <MciButton type="info">
                      <MciSvgIcon width={18} height={18} color="var(--color-grey-5)" name="more" />
                      <span class="ml-8">更多</span>
                    </MciButton>
                  </div>
                );
              },
              default() {
                return (
                  <div class="flex flex-col gap-2 node-list">
                    <div
                      class="flex items-center base-node-content"
                      onClick={async () => {
                        // const res = await getDecisionFlowGet({ flowId: props.versionFlow.id });
                        const res = await getDecisionFlowGet({ flowId: props.flowId });
                        if (res) {
                          const blob = new Blob([JSON.stringify(res, null, 2)], { type: 'application/json' });
                          FileSaver.saveAs(blob, `${props.flowName}`);
                        }
                      }}>
                      <MciSvgIcon name="export" width={18} class="ml-8" color="let(--color-grey-4)" />
                      <span class="label ml-8">导出版本</span>
                    </div>
                    <div
                      class="flex items-center base-node-content"
                      onClick={() => {
                        visibleImport.value = true;
                      }}>
                      <MciSvgIcon name="import" width={18} class="ml-8" color="let(--color-grey-4)" />
                      <span class="label ml-8">导入版本</span>
                    </div>
                  </div>
                );
              }
            }}
          </ElPopover>
        </div>

        {visibleImport.value && (
          <MciDialog
            title={'上传文件'}
            confirmHandle={() => {
              visibleImport.value = false;
            }}
            modelValue={true}
            width={500}
            customClass="max-height-dialog">
            {{
              default() {
                return (
                  <ElUpload fileList={fileList} class="upload-demo" limit={1} accept={'.json'} drag={false} auto-upload={false}>
                    {{
                      default() {
                        return <div></div>;
                      },
                      trigger() {
                        return (
                          <>
                            <MciButton>选择文件</MciButton>
                          </>
                        );
                      },
                      tip() {
                        return (
                          <>
                            <div class="el-upload__tip">限制上传1个文件，格式为 json</div>
                          </>
                        );
                      }
                    }}
                  </ElUpload>
                );
              },
              footer() {
                return (
                  <>
                    <MciButton onClick={() => (visibleImport.value = false)}>取消</MciButton>
                    <MciButton
                      type="primary"
                      onClick={() => {
                        if (fileList.value && fileList.value.length) {
                          const file = fileList.value[0]?.raw;
                          if (file) {
                            const reader = new FileReader();
                            reader.onload = (e) => {
                              try {
                                const result = e.target?.result;
                                if (result) {
                                  const json = JSON.parse(result);
                                  if (json) {
                                    json.status = 0;
                                    router.push({
                                      name: 'DecisionFlow',
                                      query: {
                                        // flowId: props.versionFlow?.id,
                                        // categoryId: props.versionFlow?.categoryId
                                        flowId: props.flowId,
                                        categoryId: props.categoryId,
                                        decisionId: props.decisionId
                                      }
                                    });
                                    // emit('refreshList');
                                    setImportJSON(props.flowId, json);
                                  }
                                  visibleImport.value = false;
                                }
                              } catch (error) {
                                console.error('error', error);
                              }
                            };
                            reader.readAsText(file);
                          }
                        }
                      }}>
                      确定
                    </MciButton>
                  </>
                );
              }
            }}
          </MciDialog>
        )}
      </>
    );
  }
});
